<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap class="h-1/1">
        <CategoryTree @node-click="handleCategoryNodeClick" />
      </ContentWrap>
    </el-col>
    <el-col :span="20" :xs="24">


      <ContentWrap>
        <!-- 搜索工作栏 -->
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          
          <el-form-item label="物资名称" prop="assetName">
            <el-input
              v-model="queryParams.assetName"
              placeholder="请输入物资名称"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>

          <el-form-item v-if="queryParams.oper != 'putin'" label="物资编号" prop="assetCode">
            <el-input
              v-model="queryParams.assetCode"
              placeholder="请输入物资编号"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          
          
          <el-form-item v-if="['borrow','returns'].includes(queryParams.oper)" label="领用人" prop="userNames">
            <el-input
              v-model="queryParams.userNames"
              placeholder="请输入领用人"
              clearable
              @keyup.enter="handleQuery"
              class="!w-240px"
            />
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              class="!w-220px"
            />
          </el-form-item>
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          
            <el-button
              type="success"
              plain
              @click="handleExport"
              :loading="exportLoading"
              v-hasPermi="['school:assets-flow:export']"
            >
              <Icon icon="ep:download" class="mr-5px" /> 导出
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>

      <!-- 列表 -->
      <ContentWrap>
        <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
          <!-- <el-table-column label="编号" align="center" prop="id" /> -->
          <!-- <el-table-column label="物资ID" align="center" prop="assetId" /> -->
          <el-table-column label="物资名称" align="center" prop="assetName" />
          <el-table-column v-if="queryParams.oper != 'putin'" label="物资编号" align="center" prop="assetCode" />
          <el-table-column label="数量" align="center" prop="count" />
          <el-table-column v-if="['putin'].includes(queryParams.oper)" label="单价（元）" align="center" prop="price" />
          <el-table-column v-if="['borrow','returns'].includes(queryParams.oper)" label="领用人" align="center" prop="userNames" />
          <el-table-column v-if="['reputin'].includes(queryParams.oper)" label="维修费用（元）" align="center" prop="price" />
          <el-table-column label="备注" align="center" prop="remark" />
          <el-table-column
            label="创建时间"
            align="center"
            prop="createTime"
            :formatter="dateFormatter"
            width="180px"
          />

        </el-table>
        <!-- 分页 -->
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>

    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AssetsFlowApi, AssetsFlowVO } from '@/api/school/assets/flow'
import CategoryTree from '../consumable/CategoryTree.vue'
import { useRoute } from 'vue-router'
const route = useRoute()

/** 物资流转 列表 */
defineOptions({ name: 'SchoolAssetsFlow' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AssetsFlowVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  categoryId: undefined,
  assetType: 1,
  assetId: undefined,
  assetCode: undefined,
  assetName: undefined,
  status: undefined,
  userNames: undefined,
  createTime: [],
  oper: '',
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AssetsFlowApi.getAssetsFlowPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}



/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AssetsFlowApi.exportAssetsFlow(queryParams)
    download.excel(data, '物资流转.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


// 路由到 oper 映射关系
const pathToAssetTypeMap = {
  '/asset/consumable/consumable-putin': 'putin',
  '/asset/consumable/consumable-borrow': 'borrow',
  '/asset/consumable/consumable-restock': 'restock',
  // 可以继续扩展更多路径
}

/** 监听路由，判断是从哪个菜单请求的，然后赋值不同的类型 */
watch(() => route.path, (path) => {
  console.log(path, '---path');
  
  // 匹配路径并赋值 assetType，如果没有匹配则设为默认值 0
  queryParams.oper = pathToAssetTypeMap[path] || 0
  console.log(queryParams.oper, '---oper');
  
}, {
  immediate: true  //立即执行一次
})

/** 处理分类被点击 */
const handleCategoryNodeClick = async (row) => {
  queryParams.categoryId = row.id
  await getList()
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>